package com.rcadmin.busi.publish.service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.rcadmin.busi.templateapi.dto.WebTemplateKeyResp;
import com.rcadmin.busi.templateapi.service.WebBlockService;
import com.rcadmin.busi.web.dao.BlockDao;
import com.rcadmin.busi.web.dao.GroupKeyDao;
import com.rcadmin.busi.web.dao.TemplateDao;
import com.rcadmin.busi.web.dao.TemplatePackageDao;
import com.rcadmin.busi.web.ddl.WebBlock;
import com.rcadmin.busi.web.ddl.WebTemplate;
import com.rcadmin.busi.web.ddl.WebTemplateGroupkey;
import com.rcadmin.busi.web.ddl.WebTemplatePackage;
import com.rcadmin.common.exception.BusiException;
import com.rcadmin.common.prop.OnlineResProp;
import com.rcadmin.common.prop.TemplateResProp;
import com.rcadmin.core.app.action.ResponseData;
import com.rcadmin.core.app.action.ResponseUtils;
import com.rcadmin.util.JsonUtils;

/**
 * 发布服务
 * 
 * @author tanson lam
 * @create 2016年10月28日
 */
@Component
public class PublishService {
	@Resource
	private TemplatePackageDao templatePackageDao;
	@Resource
	private TemplateDao templateDao;
	@Resource
	private WebBlockService webBlockService;
	@Resource
	private OnlineResProp onlineResProp;
	@Resource
	private TemplateResProp templateResProp;
	@Resource
	private GroupKeyDao groupKeyDao;
	@Resource
	private BlockDao blockDao;

	public void publishOnline(Integer userId, Integer templatePackageId)
			throws IOException {
		if (userId == null || templatePackageId == null)
			throw new IllegalArgumentException(
					"userId or templatePackageId can not be null!");
		// 拷贝模板到上线之前的临时目录下
		copyTemplatePackage2Tmp(userId, templatePackageId);
		// 为内容信息生成json的文本
		generateBlockJsonData(userId, templatePackageId);
		// 拷贝临时目录内容到正式上线目录
		copyTmp2Online(userId, templatePackageId);
	}

	/**
	 * 为内容信息生成json的文本
	 * 
	 * @param userId
	 * @param templatePackageId
	 * @throws IOException
	 */
	private void generateBlockJsonData(Integer userId, Integer templatePackageId)
			throws IOException {
		WebTemplatePackage webTemplatePackage = templatePackageDao.findOne(
				userId, templatePackageId);

		List<WebTemplate> templateList = templateDao.findByTemplatePackageId(
				userId, templatePackageId);
		if (CollectionUtils.isEmpty(templateList))
			return;
		Map<String, String> templateJsonMap = Maps.newHashMap();
		// 生成所有普通模板的json数据
		for (WebTemplate template : templateList) {
			List<WebTemplateKeyResp> templateKeyResp = webBlockService
					.listTemplateBlock(userId, templatePackageId,
							template.getTemplatePath());
			if (CollectionUtils.isEmpty(templateKeyResp))
				continue;
			ResponseData responseData = ResponseUtils.success("success");
			responseData.setResult(templateKeyResp);
			String jsonData = JsonUtils.toJson(responseData);
			templateJsonMap.put(template.getTemplatePath(), jsonData);
		}
		// 生成资源模板的json数据
		Map<String, List<WebTemplateKeyResp>> resourceBlockMap = webBlockService
				.getAllResourceBlock(userId, templatePackageId);
		for (String templateUrl : resourceBlockMap.keySet()) {
			ResponseData responseData = ResponseUtils.success("success");
			responseData.setResult(resourceBlockMap.get(templateUrl));
			String jsonData = JsonUtils.toJson(responseData);
			templateJsonMap.put(templateUrl, jsonData);
		}

		for (String tempatePath : templateJsonMap.keySet()) {
			String templateJsonFileName = tempatePath + ".json";
			templateJsonFileName = templateJsonFileName.replace("?", "");
			String jsonFilePath = onlineResProp.getUploadTempDir() + "/"
					+ userId + "/" + webTemplatePackage.getPrjUrl() + "/data/"
					+ templateJsonFileName;
			String jsonData = templateJsonMap.get(tempatePath);
			FileUtils.writeStringToFile(new File(jsonFilePath), jsonData);
		}
	}

	/**
	 * 拷贝临时目录内容到正式上线目录
	 * 
	 * @param userId
	 * @param templatePackageId
	 * @throws IOException
	 */
	private void copyTmp2Online(Integer userId, Integer templatePackageId)
			throws IOException {
		WebTemplatePackage webTemplatePackage = templatePackageDao.findOne(
				userId, templatePackageId);
		String onlineTempDirPath = onlineResProp.getUploadTempDir() + "/"
				+ userId + "/" + webTemplatePackage.getPrjUrl();
		File srcDir = new File(onlineTempDirPath);
		String onlineDirPath = onlineResProp.getUploadDir() + "/" + userId
				+ "/" + webTemplatePackage.getPrjUrl();
		File destDir = new File(onlineDirPath);
		FileUtils.copyDirectory(srcDir, destDir);
	}

	/**
	 * 拷贝模板到上线之前的临时目录下
	 * 
	 * @param userId
	 * @param templatePackageId
	 * @throws IOException
	 */
	private void copyTemplatePackage2Tmp(Integer userId,
			Integer templatePackageId) throws IOException {
		WebTemplatePackage webTemplatePackage = templatePackageDao.findOne(
				userId, templatePackageId);
		if (webTemplatePackage == null
				|| StringUtils.isEmpty(webTemplatePackage.getPrjUrl()))
			return;
		String prjDirPath = templateResProp.getUploadDir() + "/" + userId + "/"
				+ webTemplatePackage.getPrjUrl();
		File srcPrjDir = new File(prjDirPath);
		if (!srcPrjDir.exists())
			throw new BusiException("can not found srcPrjDir:" + prjDirPath);
		String onlineTempDirPath = onlineResProp.getUploadTempDir() + "/"
				+ userId + "/" + webTemplatePackage.getPrjUrl();
		File destDir = new File(onlineTempDirPath);
		destDir.deleteOnExit();
		FileUtils.copyDirectory(srcPrjDir, destDir);
	}

}
